package com.oocl.admin_platform.jms;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.log4j.Logger;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.oocl.admin_platform.dto.MerchantDTO;
import com.oocl.admin_platform.pojo.Merchant;
import com.oocl.admin_platform.service.MerchantService;
import com.oocl.admin_platform.service.factory.ServiceFactory;
import com.oocl.admin_platform.util.Base64Unit;
import com.oocl.admin_platform.util.JsonUtil;
import com.oocl.admin_platform.util.UUIDEasyUtil;

public class JMSHelper {
	private MerchantService merchantService;
	private String pathString;
	private String imageType;
	private Logger logger = Logger.getLogger(JMSHelper.class);

	public void setPathString(String pathString) {
		this.pathString = pathString;
	}

	public void setImageType(String imageType) {
		this.imageType = imageType;
	}

	private boolean save(MerchantDTO merchantDTO) {

		boolean flagid = true;
		boolean flagp = true;
		// 封装
		Merchant merchant = new Merchant();
		String[] uuid = UUIDEasyUtil.getUUIDsInCount(1);

		// base64解码
		byte[] idCard = null;
		byte[] portrait = null;

		if ((merchantDTO.getIdCard() != null)
				&& (merchantDTO.getPortrait() != null)) {
			try {
				idCard = Base64Unit.decode(merchantDTO.getIdCard());
				portrait = Base64Unit.decode(merchantDTO.getPortrait());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error("image is null.");
				return false;
				// e.printStackTrace();
			}

			merchant.setId(uuid[0]);
			merchant.setAddress(merchantDTO.getAddress());
			merchant.setIdCard(idCard);
			merchant.setPortrait(portrait);
			merchant.setStatus(merchantDTO.getStatus());
			merchant.setUname(merchantDTO.getUname());

			// 需要获取所有的路径将Uname进行拼接

			// save id card path
			String idCardPath = pathString + "/idcardimages/"
					+ merchant.getUname() + "1." + imageType;
			if (idCard == null) {
				logger.error("insert IDCard error");
			} else {
				flagid = saveImageToLocal(idCard, idCardPath);
			}
			// save portarit path
			String portraitPath = pathString + "/portraitimages/"
					+ merchant.getUname() + "2." + imageType;
			if (portrait == null) {
				logger.error("insert head error");
			} else {
				flagp = saveImageToLocal(portrait, portraitPath);
			}
			// 存入数据库，获取一个MerchantService
			if (flagid && flagp) {
				merchantService = ServiceFactory.getMerchantServiceInstance();
				if (merchantService.updateJMSMsg(merchant)) {
					logger.info("get merchant info success.");
					return true;
				}
				logger.error("fail to insert merchant.");
				return false;
			} else {
				logger.error("the info not legal");
				return false;
			}
		}
		return false;

	}

	private boolean saveImageToLocal(byte[] image, String path) {

		// 写出的路径(uuid包含所有路径)
		// String pathString = uuid;
		try {
			OutputStream out = new FileOutputStream(path);
			InputStream is = new ByteArrayInputStream(image);
			byte[] buff = new byte[1024];
			int len = 0;
			while ((len = is.read(buff)) != -1) {
				out.write(buff, 0, len);
			}
			is.close();
			out.close();
			logger.info("copy image success.");
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("fail on copy the image");
			// e.printStackTrace();
		}

		return false;

	}

	public void getMessages(String jmsConnection, String mqName) {
		try {
			ConnectionFactory factory = new ActiveMQConnectionFactory(
					jmsConnection);
			Destination queue = new ActiveMQQueue(mqName);
			Connection connection = factory.createConnection();
			connection.start();
			Session session = connection.createSession(false,
					Session.CLIENT_ACKNOWLEDGE);
			final MessageConsumer comsumer = session.createConsumer(queue);
			comsumer.setMessageListener(new MessageListener() {
				/* 监听器 回调 */
				@Override
				public void onMessage(Message arg0) {
					// TODO Auto-generated method stub
					TextMessage msMessage = (TextMessage) arg0;
					MerchantDTO merchantDTO = new MerchantDTO();
					// 将msMessage Json转成DTO

					try {
						merchantDTO = JsonUtil.toDTO(msMessage.getText());
						// System.out.println(merchantDTO.getAddress()+"==========="
						// + msMessage.getText());
						logger.info("receive MQ message success.  "
								+ merchantDTO);
						// save to DB and copy file
						if (!save(merchantDTO)) {
							// 可以写logger
							logger.error("save merchantDTO error.");
						} else {
							
							logger.info("save merchantDTO success.");
						}
						msMessage.acknowledge();
					} catch (JsonParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (JsonMappingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (JMSException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			});
		} catch (Exception e) {
			logger.error("save merchantDTO exception throw " + e.getMessage());
			// e.printStackTrace();
		}

	}

}
